<?php

class storeSettingsComponents extends sfComponents
{
  // Settings
  public function executeStoreSettings()
  {
    //$baseSettings = Doctrine_Core::getTable('Settings')->findAll();
    $baseSettings = Doctrine_Query::create()
        ->select('s.*')
        ->from('Settings s')
        ->leftJoin('s.SettingsCategory sc')
        ->where('sc.name = ?', 'Magazyn')
        ->execute();
        
    $user = $this->getUser()->getAttribute('userObject');
    $this->settings = array();
    foreach($baseSettings as $setting)
    {
      $value = Doctrine_Query::create()
          ->select('s.value')
          ->from('UserSettings s')
          ->where('s.user_id = ?', $user->getId())
          ->andWhere('s.setting_id = ?', $setting->getId())
          ->fetchOne();
          
      if(!($value instanceof UserSettings))
      {
        $value = $setting->getDefaultValue();
      }
      else $value = $value->getValue();
      $this->settings[$setting->getId()] = array(
                                                 'name' => $setting->getName(),
                                                 'value' => $value,
                                                 'description' => $setting->getDescription()
                                                 );
    }
  }
  
  public function executeDocumentsSettings()
  {
    
  }
  
  public function executeOrdersSettings()
  {
    
  }
  
  // Rest
  public function executeManageCategories()
  {
    $collection = new Doctrine_Collection('Category');
    
    function tree($root, &$collection){
      if($root instanceof BaseCategory)
      {
        if($root->getChildCategories()->count() > 0)
        {
          $collection->add($root);
          foreach($root->getChildCategories() as $child)
          {
            tree($child, $collection);
          }
        }
        else
        {
          $collection->add($root);
        }
      }
    };
    
    $r = Doctrine_Query::create()
          ->select('c.*')
          ->from('Category c')
          ->where('c.parentCategory IS NULL')
          ->fetchOne();
          
    tree($r, $collection);
    
    $this->categories = $collection;
  }
  
  public function executeManageParams()
  {
    $this->params = Doctrine_Core::getTable('Parameters')->findAll();
  }
}